﻿using SqlSugar;
using WebApi.Commons.Helpers;
using WebApi.Models.Common;
using WebApi.Models.Database.DbName;
using WebApi.Models.Views.Account;

namespace WebApi.Repository
{
    /// <summary>
    /// 账号表操作
    /// </summary>
    public class AccountRepository : Repository<AccountModel>, IScopedService
    {

        /// <summary>
        /// 根据账号密码获取用户信息
        /// </summary>
        /// <param name="account"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public AccountModel GetAccount(string account, string pwd)
        {
            var user = GetFirst(p => p.Account == account && p.Password == pwd && p.IsEnable == 1);
            return user;
        }

        /// <summary>
        /// 检测账号是否有效
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public bool CheckAccountValid(string account)
        {
            return GetFirst(p => p.Account == account && p.IsEnable == 1) != null;
        }

        /// <summary>
        /// 更新密码
        /// </summary>
        /// <param name="id"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public bool UpdatePassword(long id, string password)
        {
            var sql = AsUpdateable().SetColumns(p => p.Password == password).Where(p => p.Id == id);
            return sql.ExecuteCommandHasChange();
        }

        /// <summary>
        /// 获取账号列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<AccountModel> GetAccountList(GetAccountListRequest request, out int totalCount)
        {
            totalCount = 0;
            var sql = AsQueryable().Where(p => p.IsEnable == 1);
            if (!string.IsNullOrEmpty(request.Account))
            {
                sql.Where(p => p.Account.Contains(request.Account));
            }

            sql.OrderBy(p => p.Id, OrderByType.Desc);
            var data = sql.ToPageList(request.PageIndex, request.PageSize, ref totalCount).ToList();
            return data;
        }
    }
}
